package com.github.willisaway.core.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Set;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.CookieSpec;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.DefaultCookieSpec;
import org.apache.http.protocol.HttpContext;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

/**
 * 获取雪球的cookie
 * 
 * @author ibm
 *
 */
public class CrawlerUtil {
    public static String xueqiuCookie = null;
    public static String qqCookie = null;

    public static String getXueqiuCookie() {
        if (xueqiuCookie == null) {
            xueqiuCookie = getCookieOnline("https://xueqiu.com/");
        }
        return xueqiuCookie;
    }
    
    public static String getQQCookie(String url) {
//        if (qqCookie == null) {
//            qqCookie = getCookieOnline(url);
//        }
        return qqCookie;
    }
    
    //没成功
    public static void getXueqiuCookieOnline2025() {
        String url = "https://xueqiu.com/";
        try {
            HttpURLConnection con = (HttpURLConnection)new URL(url).openConnection();
            con.setRequestMethod("GET");
            con.setAllowUserInteraction(true);
            con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36");
            xueqiuCookie = con.getHeaderField("Set-Cookie");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //废弃
    public static void getXueqiuCookieOnlineOld() {
        String uriAPI1 = "https://xueqiu.com/";
        HttpClient client = new HttpClient();
        GetMethod getMethod = new GetMethod(uriAPI1);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
        try {
            client.executeMethod(getMethod);
            // Cookie[] cookies = client.getState().getCookies();
            // String cookie1 =
            // cookies[0].toString();//aliyungf_tc=AQAAAOjR1mjL9QUAyLY+deKpwQKBiqNU
            Header[] cookieheaders = getMethod.getResponseHeaders("Set-Cookie");

            String cookieString = null;
//			getMethod.setRequestHeader("Cookie", cookie1);
			getMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36");
//			client.executeMethod(getMethod);
//			cookies = client.getState().getCookies();getMethod.getResponseHeaders();

            for (Header header : cookieheaders) {
                String tmpValue = header.getValue();
                if (tmpValue.indexOf(";") > 0) {
                    tmpValue = tmpValue.substring(0, tmpValue.indexOf(";"));
                }

                if (cookieString == null) {
                    cookieString = tmpValue;
                } else {
                    cookieString = cookieString + "; " + tmpValue;
                }
            }
            getMethod.releaseConnection();
            xueqiuCookie = cookieString;
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    // 以下是cookie策略，未完
    class EasyCookieSpec extends DefaultCookieSpec {
        public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {

        }
    }

    class EasySpecProvider implements CookieSpecProvider {
        @Override
        public CookieSpec create(HttpContext context) {
            return new EasyCookieSpec();
        }
    }

    public CloseableHttpClient getHttpClient() {
        Registry<CookieSpecProvider> r = RegistryBuilder.<CookieSpecProvider>create()
                .register("easy", new EasySpecProvider()).build();

        CookieStore cookieStore = new BasicCookieStore();

        RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("easy").build();

        CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore)
                .setDefaultCookieSpecRegistry(r).setDefaultRequestConfig(requestConfig).build();
        return httpclient;
    }
    
    public static String getCookieOnline(String url) {
        String result = null;
        System.setProperty("webdriver.chrome.driver", ConfigUtil.getProperty("webdriver.chrome.driver"));// //"D:\\distributed\\chromedriver.exe"

        // 配置Chrome选项
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-notifications"); // 禁用通知
        options.addArguments("--start-maximized"); // 启动时最大化窗口

        // 初始化WebDriver
        WebDriver driver = new ChromeDriver(options);

        try {
            // 打开雪球登录页面
            driver.get(url);

            // 等待5秒
            Thread.sleep(5000);

            // 获取登录后的Cookie
            Set<org.openqa.selenium.Cookie> cookies = driver.manage().getCookies();
            for (org.openqa.selenium.Cookie cookie : cookies) {
//                System.out.println("Cookie Name: " + cookie.getName());
//                System.out.println("Cookie Value: " + cookie.getValue());
//                System.out.println("Cookie Domain: " + cookie.getDomain());
//                System.out.println("Cookie Path: " + cookie.getPath());
//                System.out.println("Cookie Expiry: " + cookie.getExpiry());
//                System.out.println("--------------------------------------");
                if(result==null) {
                    result = cookie.getName()+"="+cookie.getValue();
                }else {
                    result = result+"; "+cookie.getName()+"="+cookie.getValue();
                }
            }
            System.out.println("完整的cookie"+result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭浏览器
            driver.quit();
        }
        return xueqiuCookie;
    }

    public static void main(String[] args) {
        CrawlerUtil.getCookieOnline("");
        System.out.println("获取到雪球的cookie是：" + xueqiuCookie);
    }
}
